package com.simin.mall.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;

import androidx.fragment.app.Fragment;


import com.simin.base.apputils.ToastUtils;
import com.simin.base.sqlite.DiskCacheManager;
import com.simin.mall.ui.MainActivity;
import com.simin.mall.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wsm on 2016/5/26.
 * <p/>
 * Activity辅助类
 */
public class ActivityUtil {


    /**
     * 跳转至应用详情页面
     */
    public static void runToAppInfoDetailActivity(Context context) {

        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.fromParts("package", context.getPackageName(), null));
        context.startActivity(intent);

    }


    /**
     * 执行到下一个页面
     *
     * @param activity
     * @param cls            目标跳转页面
     * @param isCloseCurrent 是否关闭当前页面
     */

    public static void goForward(Activity activity, Class<?> cls, boolean isCloseCurrent) {

        activity.startActivity(new Intent(activity, cls));
        if (isCloseCurrent) activity.finish();
        activity.overridePendingTransition(R.anim.act_slide_in_right, R.anim.act_slide_out_left);

    }


    /**
     * 执行到下一个页面
     *
     * @param activity       当前Activity对象
     * @param targetAction
     * @param isCloseCurrent 是否关闭当前页面
     */
    public static void goForward(Activity activity, String targetAction, boolean isCloseCurrent) {

        activity.startActivity(new Intent(targetAction));
        if (isCloseCurrent) activity.finish();
        activity.overridePendingTransition(R.anim.act_slide_in_right, R.anim.act_slide_out_left);


    }


    /**
     * 执行到下一个页面
     *
     * @param activity 当前Activity对象
     * @param cls      目标跳转页面
     */
    public static void goForward(Activity activity, Class<?> cls, Bundle data, boolean isFinishCurrent) {

        Intent intent = new Intent(activity, cls);
        if (data != null) intent.putExtras(data);//当数据包不为空时写入数据
        activity.startActivity(intent);
        if (isFinishCurrent) activity.finish();
        activity.overridePendingTransition(R.anim.act_slide_in_right, R.anim.act_slide_out_left);

    }

    /**
     * 执行到下一个页面
     *
     * @param activity     当前Activity对象
     * @param targetAction 目标跳转页面意向
     */
    public static void goForward(Activity activity, String targetAction,
                                 Bundle data, boolean isFinishCurrent) {

        Intent intent = new Intent(targetAction);
        if (data != null) intent.putExtras(data);//当数据包不为空时写入数据
        activity.startActivity(intent);
        if (isFinishCurrent) activity.finish();
        activity.overridePendingTransition(R.anim.act_slide_in_right, R.anim.act_slide_out_left);


    }


    /**
     * 执行到下一个页面
     *
     * @param activity    当前Activity对象
     * @param cls         目标跳转页面
     * @param requestCode 页面请求码
     */
    public static void goForward(Activity activity, Class<?> cls, int requestCode) {

        activity.startActivityForResult(new Intent(activity, cls), requestCode);
        activity.overridePendingTransition(R.anim.act_slide_in_right, R.anim.act_slide_out_left);

    }


    /**
     * 执行到下一个页面
     *
     * @param activity    当前Activity对象
     * @param cls         目标跳转页面
     * @param requestCode 页面请求码
     * @param data        需要发送的数据
     */
    public static void goForward(Activity activity, Class<?> cls, int requestCode, Bundle data) {

        Intent intent = new Intent(activity, cls);
        if (data != null) intent.putExtras(data);//当数据包不为空时写入数据
        activity.startActivityForResult(intent, requestCode);
        activity.overridePendingTransition(R.anim.act_slide_in_right, R.anim.act_slide_out_left);


    }

    /**
     * 执行到下一个页面
     *
     * @param activity    当前Activity对象
     * @param fragment    当前fragment对象
     * @param cls         目标跳转页面
     * @param requestCode 页面请求码
     */
    public static void goForward(Activity activity, Fragment fragment, Class<?> cls, int requestCode) {


        fragment.startActivityForResult(new Intent(activity, cls), requestCode);
        activity.overridePendingTransition(R.anim.act_slide_in_right, R.anim.act_slide_out_left);


    }


    /**
     * 执行到下一个页面
     *
     * @param activity    当前Activity对象
     * @param fragment    当前fragment对象
     * @param cls         目标跳转页面
     * @param requestCode 页面请求码
     * @param data        需要发送的数据
     */
    public static void goForward(Activity activity, Fragment fragment, Class<?> cls,
                                 int requestCode, Bundle data) {

        Intent intent = new Intent(activity, cls);
        if (data != null) intent.putExtras(data);//当数据包不为空时写入数据
        fragment.startActivityForResult(intent, requestCode);
        activity.overridePendingTransition(R.anim.act_slide_in_right, R.anim.act_slide_out_left);


    }


    /**
     * 执行到下一个页面
     *
     * @param activity
     * @param cls            目标跳转页面
     * @param isCloseCurrent 是否关闭当前页面
     */

    public static void goForwardBtT(Activity activity, Class<?> cls, boolean isCloseCurrent) {

        activity.startActivity(new Intent(activity, cls));
        if (isCloseCurrent) activity.finish();
        activity.overridePendingTransition(R.anim.act_slide_in_bottom, R.anim.act_slide_out_top);

    }


    /**
     * 执行到下一个页面
     *
     * @param activity 当前Activity对象
     * @param cls      目标跳转页面
     */
    public static void goForwardBtT(Activity activity, Class<?> cls, Bundle data, boolean isFinishCurrent) {

        Intent intent = new Intent(activity, cls);
        if (data != null) intent.putExtras(data);//当数据包不为空时写入数据
        activity.startActivity(intent);
        if (isFinishCurrent) activity.finish();
        activity.overridePendingTransition(R.anim.act_slide_in_bottom, R.anim.act_slide_out_top);
    }


    /**
     * 页面返回，带动画
     *
     * @param activity 当前Activity对象
     */
    public static void goBack(Activity activity) {

        activity.finish();
        activity.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);


    }


    /**
     * 页面返回，带动画
     *
     * @param activity   当前Activity对象
     * @param resultCode 请求结果码
     */
    public static void goBack(Activity activity, int resultCode) {

        activity.setResult(resultCode);
        activity.finish();
        activity.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);


    }


    /**
     * 页面返回，带动画
     *
     * @param activity   当前Activity对象
     * @param resultCode 请求结果码
     * @param data       需要返回的数据
     */
    public static void goBack(Activity activity, int resultCode, Intent data) {


        activity.setResult(resultCode, data);
        activity.finish();
        activity.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);


    }

    /**
     * 跳转
     *
     * @param activity
     * @param lat
     * @param lon
     * @param address
     */
    public static void goNavigation(Activity activity, String lat, String lon, String address) {
        if (isAppInstalled(activity, "com.autonavi.minimap")) {
            Uri uri = Uri.parse("amapuri://route/plan/?dlat=" + lat + "&dlon=" + lon + "&dname=" + address + "&dev=0&t=0");
            activity.startActivity(new Intent(Intent.ACTION_VIEW, uri));
        } else if (isAppInstalled(activity, "com.baidu.BaiduMap")) {
            Uri uri = Uri.parse("baidumap://map/navi?location=" + lat + "," + lon + "&name=" + address);
            activity.startActivity(new Intent(Intent.ACTION_VIEW, uri));
        } else {
            ToastUtils.show("请先安装高德或百度地图！");
        }
    }

    /**
     * 检查指定包名的应用是否安装
     *
     * @param context     上下文对象
     * @param packageName 应用的包名
     * @return 如果安装了返回 true，否则返回 false
     */
    private static boolean isAppInstalled(Context context, String packageName) {
        PackageManager packageManager = context.getPackageManager();
        try {
            packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }


    /**
     * 强制退出应用程序
     */
    public static void abortExit() {


        System.exit(0);//java代码式退出
        android.os.Process.killProcess(android.os.Process.myUid());
        android.os.Process.killProcess(android.os.Process.myPid());
        android.os.Process.killProcess(android.os.Process.myTid());


    }

    /**
     * 关闭所有的activity
     *
     * @param context
     * @param cls     跳转目标页
     */
    public static void finishAll(Context context, Class<?> cls) {
        Intent intent = new Intent(context, cls);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        if (context instanceof Activity) {
            ((Activity) context).finish();
        }
    }


    /**
     * 登录成功，跳转首页
     *
     * @param context
     */
    public static void startMain(Context context) {
        DiskCacheManager.putBoolean(DiskCacheManager.LOGIN_STATUS, true);
        Intent intent = new Intent(context, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        if (context instanceof Activity) {
            ((Activity) context).finish();
        }
    }

    /**
     * 打开应用商店详情页
     *
     * @param activity
     */
    public static void jumpToAppStoreDetail(Activity activity, String downloadUrl) {
        ArrayList<String> appStorePackages = getInstalledAppStorePackages(activity);
        if (!CollectionUtil.isEmpty(appStorePackages)) {
            String marketPkg = appStorePackages.get(0); // 选择第一个安装的应用商店
            launchAppDetail(activity, activity.getPackageName(), marketPkg);
        } else if (StringUtils.isNotBlank(downloadUrl)) {
            // 如果没有安装应用商店，可以提示用户安装或者使用浏览器打开其他下载链接
            ToastUtils.show("未上架当前应用商店，请使用浏览器打开下载最新版本安装");
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(downloadUrl));
            activity.startActivity(intent);
        } else {
            ToastUtils.show("未上架当前应用商店");
        }
    }

    /**
     * 查询已安装应用商店列表
     *
     * @param context
     * @return
     */
    private static ArrayList<String> getInstalledAppStorePackages(Context context) {
        ArrayList<String> appStorePackages = new ArrayList<>();
        PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> installedPackages = packageManager.getInstalledPackages(0);
        for (PackageInfo packageInfo : installedPackages) {
            String packageName = packageInfo.packageName;
            // 根据已知的应用商店包名特征进行筛选
            if (packageName.contains("huawei.appmarket") || packageName.contains("xiaomi.market")
                    || packageName.contains("oppo.market") || packageName.contains("vivo.appstore")
                    || packageName.contains("hihonor.appmarket") || packageName.contains("bbk.appstore")) {
                appStorePackages.add(packageName);
            }
        }
        return appStorePackages;
    }

    /**
     * 打开应用商店详情页
     *
     * @param mContext
     * @param appPkg    目标应用包名
     * @param marketPkg 使用系统默认的market://协议来构建跳转链接
     */
    public static void launchAppDetail(Context mContext, String appPkg, String marketPkg) {
        try {
            if (TextUtils.isEmpty(appPkg)) {
                return;
            }
            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            if (!TextUtils.isEmpty(marketPkg)) {
                intent.setPackage(marketPkg);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
